package com.example.mqttdevicesimulator;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.example.mqttdevicesimulator.jsonformatinfo.RegisterInfo;
import com.example.mqttdevicesimulator.touchpad.TouchPadActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.example.mqttdevicesimulator.UtilConstants.DeviceFullName;
import static com.example.mqttdevicesimulator.UtilConstants.DeviceType;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        UtilConstants.OtherConstants.setMqttClientId(Settings.System.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID));

        Log.i(TAG, "onCreate: start MainActivity");

        initUI();

    }

    private static final int REQUEST_FILE_GET = 1;

    /**
     * Open default file explorer to get a file content.
     */
    private void selectFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_FILE_GET);
        }
    }

    /**
     * Read from the file content and select the right device activity to load.
     *
     * @param requestCode request code from the calling function
     * @param resultCode  result code
     * @param data        a file uri
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_FILE_GET && resultCode == RESULT_OK) {
            Uri fullFileUri = data.getData();
            try {
                String fileContent = readTextFromUri(fullFileUri);
                RegisterInfo deviceRegInfo = JSON.parseObject(fileContent, RegisterInfo.class);
                final String deviceInfoStr = "device_info";
                final String logiStr = "onActivityResult: transfer info: ";
                switch (deviceRegInfo.getDevice_type()) {
                    case DeviceType.LIGHT:
                        Intent lightIntent = new Intent(MainActivity.this, LightActivity.class);
                        lightIntent.putExtra(deviceInfoStr, fileContent);
                        Log.i(TAG, logiStr + fileContent);
                        startActivity(lightIntent);
                        break;
                    case DeviceType.TV:
                        Intent tvIntent = new Intent(MainActivity.this, TvActivity.class);
                        tvIntent.putExtra(deviceInfoStr, fileContent);
                        Log.i(TAG, logiStr + fileContent);
                        startActivity(tvIntent);
                        break;
                    case DeviceType.SOUNDBOX:
                        Intent soundBoxIntent = new Intent(MainActivity.this, SoundBoxActivity.class);
                        soundBoxIntent.putExtra(deviceInfoStr, fileContent);
                        Log.i(TAG, logiStr + fileContent);
                        startActivity(soundBoxIntent);
                        break;
                    case DeviceType.AIRCON:
                        Intent airconIntent = new Intent(MainActivity.this, AirconActivity.class);
                        airconIntent.putExtra(deviceInfoStr, fileContent);
                        Log.i(TAG, logiStr + fileContent);
                        startActivity(airconIntent);
                        break;
                    case DeviceType.TOUCHPAD:
                        Intent touchPadIntent = new Intent(MainActivity.this, TouchPadActivity.class);
                        touchPadIntent.putExtra(deviceInfoStr, fileContent);
                        Log.i(TAG, logiStr + fileContent);
                        startActivity(touchPadIntent);
                        break;
                    default:
                        break;
                }
            } catch (IOException e) {
                Log.e(TAG, "onActivityResult: fail to get file content from" + fullFileUri.getPath(), e);
            }

        }
    }

    /**
     * Read text content from a uri.
     *
     * @param uri
     * @return
     * @throws IOException
     */
    private String readTextFromUri(Uri uri) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream =
                     getContentResolver().openInputStream(uri);
             BufferedReader reader = new BufferedReader(
                     new InputStreamReader(Objects.requireNonNull(inputStream)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        return stringBuilder.toString();
    }

    /**
     * Initialize list and button.
     */
    private void initUI() {
        Button loadBtn = findViewById(R.id.load_device_config_btn);
        List<MqttDevice> mqttDeviceList = new ArrayList<>();

        RecyclerView deviceRecyclerView = findViewById(R.id.device_recycler_view);
//        listView = findViewById(R.id.device_list_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        deviceRecyclerView.setLayoutManager(layoutManager);

        MqttDevice light = new MqttDevice(DeviceFullName.LIGHT, R.drawable.light_pic);
        mqttDeviceList.add(light);
        MqttDevice tv = new MqttDevice(DeviceFullName.TV, R.drawable.tv_pic);
        mqttDeviceList.add(tv);
        MqttDevice soundBox = new MqttDevice(DeviceFullName.SOUNDBOX, R.drawable.sound_box_pic);
        mqttDeviceList.add(soundBox);
        MqttDevice aircon = new MqttDevice(DeviceFullName.AIRCON, R.drawable.aircon_pic);
        mqttDeviceList.add(aircon);
        MqttDevice touchPad = new MqttDevice(DeviceFullName.TOUCHPAD, R.drawable.touchpad_pic);
        mqttDeviceList.add(touchPad);

        MqttDeviceAdapter adapter = new MqttDeviceAdapter(mqttDeviceList);
        deviceRecyclerView.setAdapter(adapter);

        loadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectFile();
            }
        });
    }
}
